<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-30 11:13:49
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-04-24 18:37:26
 * @FilePath: \cxl-driving-training\src\components\form\drawer.vue
-->
<template>
    <div class="drawer-container">
        <el-drawer v-model="drawerVisible" :direction="direction" size="800" :before-close="handleClose">
            <template #header>
                <h4 style="font-size: 18px; color: #333">地址选择</h4>
            </template>
            <template #default>
                <div class="drawer-box">
                    <p>请输入所在地区获取经纬度</p>
                    <div class="" style="display: flex">
                        <el-input v-model="address" placeholder="请输入详细地址" />
                        <el-button style="margin-left: 16px" @click="getLocationByInput">定位</el-button>
                    </div>
                    <p>经度：{{ lat }}，纬度：{{ lng }}</p>
                    <div class="map"></div>
                    <div ref="mapRef" id="map-container"></div>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelClick">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ipLocation, getLocation, reverseGeocoder } from '@/apis/ip'
import axios from 'axios'

const props = defineProps(['data'])
const emits = defineEmits(['close', 'change'])

const drawerVisible = ref(false)
const direction = ref('rtl')

const address = ref('')
const mapRef = ref()

//初始默认坐标
const lat = ref(22.546693)
const lng = ref(114.032687)

let city = ''
let province = ''
let district = ''
let adcode = ''

let markers: any, map: any

const TMap = (window as any).TMap

watchEffect(() => {
    drawerVisible.value = props.data.visible
    address.value = props.data?.address

    console.log('data', props.data, mapRef.value, map)
    //监听弹窗显示
    if (props.data.visible && mapRef.value && !map) {
        //根据ip获取坐标 如果默认地址没有则通过ip获取
        if (!address.value) {
            axios.get('https://api.ipify.org').then(ip => {
                ipLocation(ip.data).then(res => {
                    if (Number(res.data.code) === 200) {
                        lat.value = res.data.result.lat
                        lng.value = res.data.result.lng
                    }
                })
            })
        }
        //初始化地图
        map = new TMap.Map(mapRef.value, {
            zoom: 14,
            center: new TMap.LatLng(lat.value, lng.value)
        })

        markers = new TMap.MultiMarker({
            map: map, //指定地图容器
            //点标记数据数组
            geometries: [
                {
                    id: '1', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                    position: new TMap.LatLng(lat.value, lng.value) //点标记坐标位置
                }
            ]
        })

        getLocationByInput()

        //监听点击事件添加marker
        map.on('click', (evt: any) => {
            console.log(evt)
            markers.updateGeometries([
                {
                    id: '1',
                    position: evt.latLng
                }
            ])
            lat.value = evt.latLng.lat
            lng.value = evt.latLng.lng

            reverseGeocoder(evt.latLng.lat, evt.latLng.lng).then(res => {
                if (Number(res.data.code) === 200) {
                    address.value = res.data.result.address
                    adcode = res.data.result.regionId
                }
            })
        })
        // ipLocation()
    }
})

//重置数据
const resetData = () => {
    city = ''
    province = ''
    district = ''
    address.value = ''
    drawerVisible.value = false
}
//取消关闭
const cancelClick = () => {
    ElMessageBox.confirm('确定要退出吗?')
        .then(() => {
            resetData()
            emits('close')
            console.log('close')
        })
        .catch(() => {
            // catch error
        })
}
//确认关闭
const confirmClick = () => {
    if (address.value) {
        emits('change', {
            address: address.value,
            lat: lat.value,
            lng: lng.value,
            province,
            city,
            district,
            adcode: adcode
        })
    } else {
        ElMessage.error('请输入详细地址')
    }
}
//退出弹窗
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要退出吗?')
        .then(() => {
            done()
            resetData()
            emits('close')
            console.log('close')
        })
        .catch(() => {
            // catch error
        })
}

//通过输入地址转换坐标
const getLocationByInput = () => {
    if (address.value) {
        getLocation(address.value).then(res => {
            if (Number(res.data.code) === 200) {
                markers.updateGeometries([
                    {
                        id: '1',
                        position: new TMap.LatLng(res.data.result.lat, res.data.result.lng)
                    }
                ])
                map.setCenter(new TMap.LatLng(res.data.result.lat, res.data.result.lng))

                lat.value = res.data.result.lat
                lng.value = res.data.result.lng
                adcode = res.data.result.regionId
            }
        })
    }
}
</script>

<style scoped>
#map-container {
    width: 100%;
    height: 600px;
}
.drawer-box p {
    line-height: 32px;
}
</style>
